<script setup>
import { reactive, ref } from 'vue';
import router from '@/router';
import loginApi from '@/api/login_api.js';
// import { adminStore, tokenStore } from '../store/store.js';
const activeIndex = ref('1')

// 取出当前登录用户的信息
const loginAdmin = ref({
  name:'',
  user_role:''
});

const menuData = ref([]);
const editWinVisible = ref(false);
const obj = ref({});

getLogin();
async function getLogin(){
  let token=localStorage.getItem('token');
  if (!token){
    //跳转到登录界面
    router.push('/login');
  }
  try {
    const res = await loginApi.logininfo();
    loginAdmin.value = res;

    if (loginAdmin.value.user_role === 1){
      menuData.value=[
        {name: '用户管理', icon: 'Avatar', children: [
            {name: '用户列表', path: "/user"},
          ]},
        {name: '书籍管理', icon: 'Reading', children: [
            {name: '书籍列表', path: "/book"},
            {name: '书籍类别', path: "/category"},
            {name: '书架列表', path: "/bookshelf"},
          ]},
        {name: '借阅管理', icon: 'Collection', children: [
            {name: '借阅记录', path: "/borrow"},
          ]},
        {name: '通知公告', icon: 'User', children: [
            {name: '公告列表', icon: 'UserFilled', path: "/notion"},
          ]},
      ];
      router.push('/user');
    }else if (res.user_role === 0) {
      menuData.value=[
        {name: '馆藏书籍', icon: 'Notebook', children: [
            {name: '书籍列表', icon: 'Document', path: "/user_book"},
          ]},
        {name: '我的借阅', icon: 'Collection', children: [
            {name: '借阅记录', path: "/borrow_records"},
          ]},
        {name: '通知公告', icon: 'User', children: [
            {name: '公告列表', icon: 'UserFilled', path: "/user_notion"},
          ]},
      ];
      router.push('/user_book');
    } else {
      // 未知角色处理
      console.warn('未知的用户角色:', res.user_role);
      router.push('/login');
    }
  } catch (error) {
    // 处理获取用户信息失败的情况
    console.error('获取用户信息失败:', error);
    localStorage.removeItem('token'); // 清除无效token
    router.push('/login');
  }

}

// 用户下拉菜单的点击
function handleSelect(key, keyPath){
  if (key == 'logout'){
    // 用户退出
    logout();
  }else if(key=='1-2'){
    router.push('/editpassword');
  } else if(key=='1-1'){ // 添加修改信息处理
    handleEditInfo();
  }
}

// 处理修改信息
const handleEditInfo = async () => {
  try {
    const res = await loginApi.logininfo();
    // 只复制需要编辑的字段，避免包含密码等敏感信息
    obj.value = {
      id: res.id,
      user_account: res.user_account,
      user_name: res.user_name,
      user_email: res.user_email,
      user_avatar: res.user_avatar
    };
    editWinVisible.value = true;
  } catch (error) {
    console.error('获取用户信息失败:', error);
  }
}

// 编辑取消
const editCancel = () => {
  obj.value = {};
  editWinVisible.value = false;
}

// 编辑提交 - 只提交非敏感字段
const editCommit = async () => {
  try {
    // 创建一个不包含密码的更新对象
    const updateData = {
      id: obj.value.id,
      user_account: obj.value.user_account,
      user_name: obj.value.user_name,
      user_email: obj.value.user_email,
      user_avatar: obj.value.user_avatar
    };

    await api.edit(updateData);

    // 更新成功后刷新用户信息
    const res = await loginApi.logininfo();
    loginAdmin.value = res;
    editWinVisible.value = false;
  } catch (error) {
    console.error('更新用户信息失败:', error);
  }
}

// 左侧菜单动作
function handleMenu(key){
  if (key){
    router.push(key);
  }
}
// 退出
function logout(){
  // 清除Token
  localStorage.removeItem('token');
  // 跳转到登录
  router.push('/login')
}

// 左侧菜单展开折叠
const isCollapse = ref(false);
</script>


<template>
  <div class="common-layout">

    <el-container>
      <el-header>
        <el-menu :default-active="activeIndex"
                 class="el-menu-demo"
                 mode="horizontal"
                 :ellipsis="false"
                 background-color="#f3f7ff"
                 text-color="#393939"
                 active-text-color="#ffd04b"
                 @select="handleSelect">

          <el-menu-item index="0">
            <img style="height: 80%" src="@/assets/logo1.jpg" alt="黄金屋" />
            <span style="padding-left: 50px; font-size: 24px; color:#393939;">黄金屋-图书借阅管理系统</span>
          </el-menu-item>
          <div class="flex-grow" />
          <el-sub-menu index="1">
            <template #title>
              <el-icon><Stamp></Stamp></el-icon>
              {{ loginAdmin?loginAdmin.user_name:'没登录' }}
            </template>
<!--            <el-menu-item index="1-1">修改信息</el-menu-item>-->
            <el-menu-item index="1-2">修改密码</el-menu-item>
            <el-menu-item index="logout">退出
              <el-icon><SwitchButton></SwitchButton></el-icon>
            </el-menu-item>
          </el-sub-menu>

        </el-menu>
      </el-header>
      <el-container>
        <el-aside :width="1">
          <div style="height: 60px;line-height: 60px; text-align: right; color: #FFF; font-size: 20px; margin-right: 24px;">
            <el-icon @click="isCollapse=!isCollapse">
              <Expand v-if="isCollapse"></Expand>
              <Fold v-else></Fold>
            </el-icon>
          </div>
          <el-menu active-text-color="#ffd04b" background-color="#0c1d40" class="el-menu-vertical-demo"
                   default-active="/charts" text-color="#fff" :collapse="isCollapse"
                   @select="handleMenu">
            <!-- 动态生成菜单 -->
            <el-sub-menu v-for="(menu, index) in menuData" :index="index.toString()">
              <template #title>
                <component
                    class="icons"
                    :is="menu.icon"
                    style="width: 1em; height: 1em; margin-right: 8px" >
                </component>
                <span>{{ menu.name }}</span>
              </template>
              <el-menu-item v-for="(child, ind) in menu.children" :index="child.path">
                <el-icon><component
                    :is="child.icon">
                </component></el-icon>
                <span>{{ child.name }}</span>
              </el-menu-item>
            </el-sub-menu>

          </el-menu>
        </el-aside>
        <el-main>
          <router-view></router-view>
        </el-main>
      </el-container>
    </el-container>
  </div>

  <!--编辑对话框-->
  <el-dialog v-model="editWinVisible" title="编辑" width="500">
    <el-form :model="obj">
      <el-form-item label="用户账号" :label-width="100">
        <el-input v-model="obj.user_account"  autocomplete="off" />
      </el-form-item>
      <el-form-item label="用户昵称" :label-width="100">
        <el-input v-model="obj.user_name"  autocomplete="off" />
      </el-form-item>
      <!--      <el-form-item label="用户密码" :label-width="100">-->
      <!--        <el-input v-model="obj.user_password"  autocomplete="off" />-->
      <!--      </el-form-item>-->
      <el-form-item label="用户邮箱" :label-width="100">
        <el-input v-model="obj.user_email"  autocomplete="off" />
      </el-form-item>
      <el-form-item label="用户头像" :label-width="100">
        <el-upload
            class="avatar-uploader"
            action="/api/upload/file"
            :show-file-list="false"
            :on-success="handleUploadSuccess"
        >
          <img  v-if="obj.photo" :src="obj.photo"  style="width:100px" />
          <img v-else src='../assets/管理员.jpg' style="width:100px"/>
        </el-upload>
      </el-form-item>

    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="editCancel">取消</el-button>
        <el-button type="primary" @click="editCommit">
          提交
        </el-button>
      </div>
    </template>
  </el-dialog>

</template>



<style>
.flex-grow {
  flex-grow: 1;
}

.common-layout,
.el-container {
  height: 100vh;
}

.el-header {
  --el-header-padding: 0;
  --el-header-height: 80px;
  box-sizing: border-box;
  flex-shrink: 0;
  height: var(--el-header-height);
  padding: var(--el-header-padding);
}

.el-menu--horizontal {
  height: 80px;
}

.el-aside {
  background-color: #0c1d40;
}

.el-main{
  padding: 0px;
}

.el-menu{
  border-width: 0px;
}
.el-menu-item{
  font-size: 16px;
}
.el-menu-demo{
  box-shadow: 0 2px 4px rgba(0,0,0,0.25);
}

.el-sub-menu__title{
  font-size: 16px;
}

</style>